package controllers

import (
	"encoding/json"
	"portstoragechanges/models"
	"portstoragechanges/pkg/app"
	"portstoragechanges/pkg/e"
	"portstoragechanges/services"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func Getdelivery(c *gin.Context) {
	err, data := services.Getdelivery()
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
	}
	app.OK(c, gin.H{"value": data}, "查询成功")
}

func Deldelivery(c *gin.Context) {
	id := "-1"
	id = c.Query("port_id")
	//fmt.Println(id)
	if id == "" {
		app.INFO(c, 30001, "参数错误")
		return
	}
	err := services.Deldelivery(id)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, gin.H{"value": id}, "删除成功")
}

func Updatedelivery(c *gin.Context) {
	a, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(a, &m)
	delivery_id := m["delivery_id"]
	delivery_date := m["delivery_date"]
	delivery_piece := com.StrTo(m["delivery_piece"]).MustInt()
	delivery_ton := m["delivery_ton"]
	delivery_surplus := com.StrTo(m["delivery_surplus"]).MustInt()

	err := services.Updatedelivery(models.Deldelivery{delivery_id, delivery_date, delivery_piece, delivery_ton, delivery_surplus})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, gin.H{}, "更新成功！")
}

func Adddelivery(c *gin.Context) {
	a, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(a, &m)
	delivery_id := m["delivery_id"]
	delivery_date := m["delivery_date"]
	delivery_piece := com.StrTo(m["delivery_piece"]).MustInt()
	delivery_ton := m["delivery_ton"]
	delivery_surplus := com.StrTo(m["delivery_surplus"]).MustInt()

	err := services.Updatedelivery(models.Deldelivery{delivery_id, delivery_date, delivery_piece, delivery_ton, delivery_surplus})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, gin.H{}, "添加成功！")
}
